<template>
   <div>
    <van-nav-bar title="登录" />
    <van-form @submit="onSubmit">
      <!-- vant提供的输入框 -->
      <van-field
        v-model="info.mobile"
        label="手机号"
        placeholder="请输入手机号"
        :rules="rules.mobile"
      />
      <van-field
        v-model="info.code"
        label="验证码"
        placeholder="请输入验证码"
        :rules="rules.code"
      />
      <div style="margin: 16px">
        <van-button :loading="isLoading"
          loading-text="登录中..." round block type="info" native-type="submit"
          >登录</van-button
        >
      </div>
    </van-form>
   </div>
</template>

<script>
import { loginAPI } from '@/api'
// 文档中的Toast写法，是局部写法。要哪里用就哪里导入
import { Toast } from 'vant'
export default {
    components: {},
    props: {},
    data() {
        return {
            isLoading:false,
            info:{
                mobile: '18207548347',
                code: '246810',
            },
            rules: {
                // 手机号的规则
                mobile: [
                    // required：代表是否必填
                    // message: 如果没满足规则，弹出的提示
                    { required: true, message: '请输入手机号' },
                    // 用来验证输入的是不是手机号
                    { pattern:/^1[2-9]\d{9}$/, message: '请输入正确的手机号' }
                ],
                // 验证码的规则
                code: [
                    { required: true, message: '请填写验证码' },
                    { pattern: /^\d{6}$/, message: '请输入6位数字验证码' }
                ]
            }
        };
    },
    computed:{},
    watch:{},
    created () {},
    mounted () {},
    methods: {
        async onSubmit () {
            // 一点击就要显示加载状态
            this.isLoading = true;
            try {
                let res = await loginAPI(this.info);
                console.log(res);
                this.$store.commit('changeToken', res.data.data)
                // 在登录成功后，判断有没有参数，有就跳转到参数对应的路径，没有就跳转到首页
                if(this.$route.query.back){
                    //跳转到这个参数对应的值的路径上
                    this.$router.push(this.$route.query.back)
                }else{
                    this.$router.push('/layout/home')
                }
                //把userInfo清空
                this.$store.commit('changeUserInfo', {})
            } catch {
                alert('验证码错误')
            }
            // 不管登录成功还是失败，最后都把加载状态改为false
            this.isLoading = false;
        }
    },
}
</script>
<style scoped>

</style>